import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/views/layout'
import { getToken } from '@/utils/storage'
Vue.use(VueRouter)

const Detail = () => import('@/views/detail')
const Login = () => import('@/views/login')
const Article = () => import('@/views/article')
const User = () => import('@/views/user')
const Search = () => import('@/views/search')
const Technology = () => import('@/views/technology')

const router = new VueRouter({
  routes: [
    {
      path: '/',
      component: Layout,
      redirect: '/article',
      children: [
        { path: '/article', component: Article },
        { path: '/user', component: User },
        { path: '/search', component: Search }
      ]
    },
    { path: '/detail/:id', component: Detail },
    { path: '/technology', component: Technology },
    { path: '/login', component: Login }
  ]
})

const whiteList = ['/login']
router.beforeEach((to, from, next) => {
  const token = getToken()
  if (token) {
    next()
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
